package com.ruoyi.framework.security.auth;
import java.util.Date;
import java.util.HashMap;
import org.springframework.stereotype.Component;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ruoyi.common.utils.DateUtils;

/**
 * token认证
 * @author liuz
 */
@Component
public class JwtUtil {

	/**
	 * token私钥
	 */
	private static final String TOKEN_SECRET = "joijsdfjl_!@#!@#_POIJJJELWIQKDJ@#4334";

	/**
	 * 生成签名,15分钟后过期
	 * @param userId
	 * @param nickname
	 * @param phone
	 * @return
	 */
	public String sign(String userId,String nickname,String phone){
		//过期时间
		// Date date = new Date(System.currentTimeMillis() + 30000);
		Date date = DateUtils.addDateForMonths(new Date(), 6);
		//System.out.println(DateUtil.format(date, DateUtil.DATE_TIME_FORMAT));
		//私钥及加密算法
		Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
		//设置头信息
		HashMap<String, Object> header = new HashMap<>(2);
		header.put("typ", "JWT");
		header.put("alg", "HS256");
		//附带username和userID生成签名
		return JWT.create().withHeader(header)
				.withClaim("id",userId)
				.withClaim("nickname",nickname)
				.withClaim("phone",phone)
				.withExpiresAt(date).sign(algorithm);
	}

	public static boolean verity(String token){
		try {
			Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
			JWTVerifier verifier = JWT.require(algorithm).build();
			verifier.verify(token);
			return true;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			return false;
		} catch (JWTVerificationException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 从token中获取用户信息
	 *
	 * @param token token
	 * @return JWTUser
	 */
	public static JWTUser getUserFromToken(String token){
		if(!JwtUtil.verity(token)){return null;}
		DecodedJWT jwt = JWT.decode(token);
		JWTUser user = new JWTUser();
		user.setId(Long.parseLong(jwt.getClaim("id").asString()));
		user.setNickname(jwt.getClaim("nickname").asString());
		user.setPhone(jwt.getClaim("phone").asString());
		return user;
	}
}
